//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Eas.WebCrawler.Common.IO {
    /// <summary>A static helper class used to copy contents between <see cref="System.IO.Stream"/>s using readers and writers.</summary>
    /// <remarks>This class will still perform correctly even if your readers and writers do not have backing <see cref="System.IO.Stream"/>s.</remarks>
    public static class StreamCopier {
        /// <summary>Copies the output of a reader into a wrtter.</summary>
        /// <param name="reader">The <see cref="TextReader"/> from which contents will be read.</param>
        /// <param name="writer">The <see cref="TextWriter"/> to which contents will be written.</param>
        /// <param name="blockSize">The number of characters to copy at one time.</param>
        /// <remarks>A larger block size will mean less calls to the underlying reader and writer but it will use more memory.</remarks>
        public static void CopyTextStreams(TextReader reader, TextWriter writer, int blockSize) {
            char[] buffer = new char[blockSize];
            int charCount;
            do {
                charCount = reader.ReadBlock(buffer, 0, blockSize);
                writer.Write(buffer, 0, charCount);
            } while (charCount == blockSize);
        }

        /// <summary>Copies the output of a reader into a writter.</summary>
        /// <param name="reader">The <see cref="BinaryReader"/> from which contents will be read.</param>
        /// <param name="writer">The <see cref="BinaryWriter"/> to which contents will be written.</param>
        /// <param name="blockSize">The number of characters to copy at one time.</param>
        /// <remarks>A larger block size will mean less calls to the underlying reader and writer but it will use more memory.</remarks>
        public static void CopyBinaryStreams(BinaryReader reader, BinaryWriter writer, int blockSize) {
            byte[] buffer = new byte[blockSize];
            int byteCount;
            do {
                byteCount = reader.Read(buffer, 0, blockSize);
                writer.Write(buffer, 0, byteCount);
            } while (byteCount == blockSize);
        }
    }
}
